import {
  AwaitedReactNode,
  JSXElementConstructor,
  ReactElement,
  ReactNode,
  ReactPortal,
  createContext,
  useEffect,
  useState,
  useRef,
} from 'react'

import API, { AssistantListProps } from '@/services'

interface IGlobalContextProps {
  insData: any
  setInsData: (data: any) => void
}

export const GlobalContext = createContext<IGlobalContextProps>({
  insData: {},
  setInsData: () => {},
})

export const GlobalContextProvider = (props: { children: React.ReactNode }) => {
  const fetchRef = useRef(false)
  const [currentInfos, setCurrentInfos] = useState<AssistantListProps[]>()

  useEffect(() => {
    const getAssistantInfos = async () => {
      fetchRef.current = true
      const data = await API.getAssistantInfo()
      setCurrentInfos(data)
      fetchRef.current = false
    }
    !fetchRef.current && getAssistantInfos()
  }, [])

  return (
    <GlobalContext.Provider
      value={{
        insData: currentInfos,
        setInsData: setCurrentInfos,
      }}
    >
      {props.children}
    </GlobalContext.Provider>
  )
}
